package com.autoagent.ai_live_master.scriptRecommendation.controller;

import com.autoagent.ai_live_master.common.base.ApiResponse;
import com.autoagent.ai_live_master.scriptRecommendation.entity.LiveStreamingPlan;
import com.autoagent.ai_live_master.scriptRecommendation.dto.LiveStreamingPlanDTO;
import com.autoagent.ai_live_master.scriptRecommendation.service.LiveStreamingPlanService;
import com.autoagent.ai_live_master.common.base.UserContext;
import com.autoagent.ai_live_master.common.event.LiveStreamingPlanEvent;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/liveStreamingPlan")
public class LiveStreamingPlanController {

    @Autowired
    private LiveStreamingPlanService liveStreamingPlanService;
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @PostMapping
    public ApiResponse<Boolean> create(@RequestBody LiveStreamingPlan plan) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        plan.setUserId(userId);
        log.info("创建直播计划配置: {}", plan);
        boolean saved = liveStreamingPlanService.save(plan);
        if (saved) {
            return ApiResponse.success(true);
        } else {
            log.error("创建直播计划配置失败: {}", plan);
            return ApiResponse.error(500, "创建失败");
        }
    }

    @GetMapping("/{id}")
    public ApiResponse<LiveStreamingPlan> getById(@PathVariable Long id) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        log.info("查询直播计划配置，userId={}, id={}", userId, id);
        LiveStreamingPlan plan = liveStreamingPlanService.getById(id);
        if (plan != null) {
            // 验证是否属于当前用户
            if (!plan.getUserId().equals(userId)) {
                log.warn("直播计划配置不属于当前用户，userId={}, planId={}", userId, id);
                return ApiResponse.error(403, "无权限访问该数据");
            }
            return ApiResponse.success(plan);
        } else {
            log.warn("直播计划配置未找到，userId={}, id={}", userId, id);
            return ApiResponse.error(404, "数据未找到");
        }
    }

    @PutMapping("/{id}")
    public ApiResponse<Boolean> update(@PathVariable Long id, @RequestBody LiveStreamingPlan plan) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        log.info("更新直播计划配置，userId={}, id={}, 数据: {}", userId, id, plan);
        plan.setId(id.intValue());
        plan.setUserId(userId);
        boolean updated = liveStreamingPlanService.updateById(plan);
        if (updated) {
            return ApiResponse.success(true);
        } else {
            log.error("更新直播计划配置失败，userId={}, id={}, 数据: {}", userId, id, plan);
            return ApiResponse.error(500, "更新失败");
        }
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> delete(@PathVariable Long id) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        log.info("删除直播计划配置，userId={}, id={}", userId, id);
        // 先检查是否存在且属于当前用户
        LiveStreamingPlan plan = liveStreamingPlanService.getById(id);
        if (plan == null) {
            log.warn("直播计划配置未找到，userId={}, id={}", userId, id);
            return ApiResponse.error(404, "数据未找到");
        }
        if (!plan.getUserId().equals(userId)) {
            log.warn("直播计划配置不属于当前用户，userId={}, planId={}", userId, id);
            return ApiResponse.error(403, "无权限删除该数据");
        }
        boolean removed = liveStreamingPlanService.removeById(id);
        if (removed) {
            return ApiResponse.success(true);
        } else {
            log.error("删除直播计划配置失败，userId={}, id={}", userId, id);
            return ApiResponse.error(500, "删除失败");
        }
    }

    @GetMapping("/page")
    public ApiResponse<IPage<LiveStreamingPlanDTO>> page(@RequestParam int pageNum, @RequestParam int pageSize) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        log.info("分页查询直播计划配置，userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize);
        IPage<LiveStreamingPlanDTO> page = liveStreamingPlanService.getPageByUserId(userId, pageNum, pageSize);
        return ApiResponse.success(page);
    }

    @Operation(summary = "启用直播计划", description = "启用指定ID的直播计划")
    @PostMapping("/{id}/enable")
    public ApiResponse<Boolean> enableLiveStreamingPlan(
            @Parameter(description = "直播计划ID", required = true)
            @PathVariable Integer id) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        log.info("启用直播计划, userId={}, ID: {}", userId, id);
        try {
            // 获取直播计划
            LiveStreamingPlan liveStreamingPlan = liveStreamingPlanService.getById(id);
            if (liveStreamingPlan == null) {
                throw new RuntimeException("直播计划不存在");
            }
            // 验证是否属于当前用户
            if (!liveStreamingPlan.getUserId().equals(userId)) {
                throw new RuntimeException("无权限操作该直播计划");
            }

            boolean enabled = liveStreamingPlanService.enableLiveStreamingPlan(id);
            if (enabled) {
                // 发布直播计划启动事件
                eventPublisher.publishEvent(new LiveStreamingPlanEvent(
                    this, 
                    String.valueOf(liveStreamingPlan.getLiveRoomId()), 
                    "start", 
                    Long.valueOf(id),
                    liveStreamingPlan.getScriptId()
                ));
                return ApiResponse.success(true);
            } else {
                log.error("启用直播计划配置失败，userId={}, id={}", userId, id);
                return ApiResponse.error(500, "启用失败");
            }
        } catch (Exception e) {
            log.error("启用直播计划失败: {}", e.getMessage());
            if (e.getMessage().contains("无权限")) {
                return ApiResponse.error(403, e.getMessage());
            } else if (e.getMessage().contains("不存在")) {
                return ApiResponse.error(404, e.getMessage());
            }
            return ApiResponse.error(500, "启用直播计划失败: " + e.getMessage());
        }
    }

    @Operation(summary = "禁用直播计划", description = "禁用指定ID的直播计划")
    @PostMapping("/{id}/disable")
    public ApiResponse<Boolean> disableLiveStreamingPlan(
            @Parameter(description = "直播计划ID", required = true)
            @PathVariable Integer id) {
        // 获取当前登录用户ID
        Long userId = UserContext.getCurrentUserId();
        log.info("禁用直播计划, userId={}, ID: {}", userId, id);
        try {
            // 获取直播计划
            LiveStreamingPlan liveStreamingPlan = liveStreamingPlanService.getById(id);
            if (liveStreamingPlan == null) {
                throw new RuntimeException("直播计划不存在");
            }
            // 验证是否属于当前用户
            if (!liveStreamingPlan.getUserId().equals(userId)) {
                throw new RuntimeException("无权限操作该直播计划");
            }

            boolean disabled = liveStreamingPlanService.disableLiveStreamingPlan(id);
            if (disabled) {
                // 发布直播计划停止事件
                eventPublisher.publishEvent(new LiveStreamingPlanEvent(
                    this, 
                    String.valueOf(liveStreamingPlan.getLiveRoomId()), 
                    "stop", 
                    Long.valueOf(id),
                    liveStreamingPlan.getScriptId()
                ));
                return ApiResponse.success(true);
            } else {
                log.error("禁用直播计划配置失败，userId={}, id={}", userId, id);
                return ApiResponse.error(500, "禁用失败");
            }
        } catch (Exception e) {
            log.error("禁用直播计划失败: {}", e.getMessage());
            if (e.getMessage().contains("无权限")) {
                return ApiResponse.error(403, e.getMessage());
            } else if (e.getMessage().contains("不存在")) {
                return ApiResponse.error(404, e.getMessage());
            }
            return ApiResponse.error(500, "禁用直播计划失败: " + e.getMessage());
        }
    }

    @Operation(summary = "根据房间ID获取启用的直播计划", description = "根据直播间房号获取对应的启用的直播计划")
    @GetMapping("/room/{roomId}")
    public ApiResponse<LiveStreamingPlan> getEnabledPlanByRoomId(
            @Parameter(description = "直播间房号", required = true)
            @PathVariable String roomId) {
        try {
            log.info("根据房间ID查找启用的直播计划，房间ID: {}", roomId);
            LiveStreamingPlan plan = liveStreamingPlanService.findEnabledPlanByRoomId(roomId);
            if (plan != null) {
                return ApiResponse.success(plan);
            } else {
                log.warn("未找到启用的直播计划，房间ID: {}", roomId);
                return ApiResponse.error(404, "未找到启用的直播计划");
            }
        } catch (Exception e) {
            log.error("根据房间ID查找直播计划失败，房间ID: {}, 错误信息: {}", roomId, e.getMessage(), e);
            return ApiResponse.error(500, "查找直播计划失败");
        }
    }
}

